//
//  Book.m
//  BookMaker
//
//  Created by Mathieu Tozer on 22/11/07.
//  Copyright 2007 plasq. All rights reserved.
//

#import "Book.h"
#import "Image.h"
#import "CoreData+Additions.h"

@implementation Book

- (void)awakeFromInsert
{
	[self setValue:NSStringFromRect(NSMakeRect(0.0, 0.0, 509, 717)) forKey:@"targetRect"]; //sony reader including 0.25 inch margins
}

- (BOOL)isValidImageFile:(NSString *)path
{
	return YES; //todo implement
}

- (Image *)imageObjectForFileAtPath:(NSString *)path order:(int)order
{
	//make or create
	NSManagedObject *image = [[self managedObjectContext] findOrCreateObjectOfEntityType:@"Image" usingKey:@"path" andValue:path];
	[(Image *)image setOrder:order];
	[[self mutableSetValueForKey:@"images"] addObject:image]; 
//	[(Image *)image addDefaultPagesForBook:self];
	return (Image *)image;
}

- (void)createImageObjectsForFiles:(NSArray *)files inDir:(NSString *)dir
{
	NSMutableArray *images = [[NSMutableArray alloc] init];
	int order = 0;
	for (NSString *file in files) {
		[images addObject:[self imageObjectForFileAtPath:[[dir stringByAppendingPathComponent:file] stringByAbbreviatingWithTildeInPath] order:order]];
		order++;
		
	}
}

- (void)setPath:(NSString *)path
{
	//overriding so that we can kick off the creation of image objects for all the images found at path
	
	NSFileManager *fm = [NSFileManager defaultManager];
	BOOL isDir = NO;
	NSArray *files = nil;
	if ([fm fileExistsAtPath:[path stringByExpandingTildeInPath] isDirectory:&isDir]) {
		if (isDir) {
			files = [fm directoryContentsAtPath:[path stringByExpandingTildeInPath]];
		}
	}
	if (files) {
		[self createImageObjectsForFiles:files inDir:path];	
	}
	
	[self setPrimitiveValue:[path stringByAbbreviatingWithTildeInPath] forKey:@"dirPath"];
}

- (NSString *)targetRectString
{
	return [self primitiveValueForKey:@"targetRect"];
}

- (NSRect)targetRect
{
	return NSRectFromString([self primitiveValueForKey:@"targetRect"]);
}

- (float)effectiveAspectRatio
{
	NSRect rect = [self targetRect];
	float ratio = rect.size.width / rect.size.height;
	return ratio;
}
@end
